(function () {
	//自定义true标签对象
	function trueCharts(){}
	trueCharts.prototype = {
		//弹出窗体
		getDomHtml:function(){
			return '<div class="tw-window tw-winpn tw-window-dataImport">\
				<div class="tw-close-cross">X</div>\
				<div class="tw-window-con">\
					<div class="tw-layout-title">插入图表</div>\
					<div class="tw-import-wrap">\
						<div class="tw-tabs JS_tabs">\
							<ul class="tw-tabs-head" style="display:none">\
								<li data-type="0"><a href="javascript:;"></a></li>\
								<li data-type="1"><a href="javascript:;"></a></li>\
								<li data-type="2"><a href="javascript:;"></a></li>\
								<li data-type="3"><a href="javascript:;"></a></li>\
								<li data-type="4"><a href="javascript:;"></a></li>\
							</ul>\
							<div class="tw-tabs-body" style="overflow-y:auto;overflow-x:hidden;">\
								<div class="tw-tabs-con">\
									<div class="tw-form tw-pro">\
										<div class="row">\
											<label>选择指标:</label>\
											<div>\
												<select class="JS_zhibiao form-control input-sm chosen-select"></select>\
											</div>\
										</div>\
										<div class="row yaosu">\
										</div>\
										<div class="row leixing">\
											<label>选择图表类型:</label>\
											<div class="small">\
												<select class="JS_ctype form-control input-sm chosen-select">\
												<option value="2">地区</option>\
												<option value="3">时间</option>\
												</select>\
											</div>\
										</div>\
										<div class="row group">\
										</div>\
									</div>\
								</div>\
								<div class="tw-tabs-con">\
								</div>\
								<div class="tw-tabs-con">\
									<div class="tw-form tw-pro">\
										<div class="row">\
										</div>\
									</div>\
								</div>\
								<div class="tw-tabs-con timer">\
									<div class="tw-form tw-pro">\
									</div>\
									<div class="tw-btnw">\
										<span class="tw-btnm custom save JS_next_step step4" style="display:none">生成计算因子</span>\
									</div>\
								</div>\
								<div class="tw-tabs-con option">\
									<div class="tw-form tw-pro notClear">\
										<div class="row">\
											<label>宽度:</label>\
											<div style="width:90px">\
												<input style="width:90px" type="text" class="form-control input-sm JS_chartWidth" value="400">\
											</div>\
											<label>高度:</label>\
											<div style="width:90px">\
												<input style="width:90px" type="text" class="form-control input-sm JS_chartHeight" value="300">\
											</div>\
										</div>\
										<div class="row">\
										</div>\
									</div>\
									<div class="tw-btnw">\
										<span class="tw-btnm custom save JS_btnChartSetting notClear">配置图表</span>\
										<span class="tw-btnm custom save JS_btnChartInsert notClear" style="display:none">确认保存</span>\
										<span class="tw-btnm custom save JS_btnInsertTable notClear" style="display:none">插入表格</span>\
										<span class="tw-btnm custom save JS_next_step step5" style="display:none">确认运算公式</span>\
									</div>\
								</div>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>';
		},
		
		//时间选择的结构
		getTimerHtml:function(){
			var condMonthOption = '';
			//当年
			var yearNow = new Date().getFullYear();
			this.yearNow = yearNow;
			var condYearOption = '';
			for ( var i = (yearNow-3); i<=(yearNow+3); i++ ){
                condYearOption += '<option value ="'+ i +'">'+ i +'</option>';
            }
			condYearOption += '<option value ="'+ this.nowY +'">当前年</option>';
			//当月
			var monthNow = new Date().getMonth()+1;
			this.monthNow = monthNow;
			for ( var i = 1; i<=12; i++ ){
                condMonthOption += '<option value ="'+ i +'">'+ i +'</option>';
            }
			condMonthOption += '<option value ="'+ this.nowM +'">当前月</option>';
//			var html = '<div class="row">\
//						<label>选择年份:</label>\
//						<div class="small">\
//							<select class="JS_timerStartMonth form-control input-sm chosen-select">\
//							'+condYearOption+'\
//							</select>\
//						</div>\
//						<label>选择起始月份（至当月）:</label>\
//						<div class="small">\
//							<select class="JS_timerEndMonth form-control input-sm chosen-select">\
//							'+condMonthOption+'\
//							</select>\
//						</div>\
//					</div>';
					
			var html = '<div class="row">\
							<label>选择类型:</label>\
							<div class="small">\
								<select class="JS_timerTyper form-control input-sm chosen-select chosen-select">\
									<option value="year">年度</option>\
									<option value="month">月度</option>\
								</select>\
							</div>\
						</div>\
						<div class="row">\
							<label>(起)选择年份:</label>\
							<div class="small">\
								<select class="JS_timerStartYear form-control input-sm chosen-select chosen-select">\
								'+condYearOption+'\
								</select>\
							</div>\
							<label>选择月份:</label>\
							<div class="small">\
								<select class="JS_timerStartMonth form-control input-sm chosen-select chosen-select">\
								'+condMonthOption+'\
								</select>\
							</div>\
						</div>';
				html += '<div class="row">\
							<label>(止)选择年份:</label>\
							<div class="small">\
								<select class="JS_timerEndYear form-control input-sm chosen-select chosen-select">\
								'+condYearOption+'\
								</select>\
							</div>\
							<label>选择月份:</label>\
							<div class="small">\
								<select class="JS_timerEndMonth form-control input-sm chosen-select chosen-select">\
								'+condMonthOption+'\
								</select>\
							</div>\
						</div>';
			return html;
		},
		
		//对象初始化
		init:function(options){
			var that = this;
			//true标签的配置
			this.config = {
				//接口根路径
				//data
				//接口参数
				//debug开关，开启后用本地随机数据
				basePath:'/trueMAEC',//http://192.168.0.25:5012
				dataPath:'/trueMAEC/trueDataController/online.do',
				deptid:'{BFA80019-0000-0000-432B-267E0000000E}',
				debugEnable:false
			};
			
			//全局true标签num
			this.globalNum = 1;
			//随机true标签id前缀
			this.idPrefix = 'tags_' + Math.random().toString().replace('.', '') + '_';
			//是否进入编辑状态
			this.isEditing = false;
			//临时数据存储
			this.tmpData = {};
			//封装好的最终数据
			this.dataJSON = {};
			//当前编辑对象ID
			this.currentId = false;
			//当前年月函数
			this.nowY = '当前年';//'year(sysdate())';
			this.nowM = '当前月';//'month(sysdate())';
			//合并配置
			if(options){
				this.updateOption(options);
			}
			
			//定义弹出层大小
			this.updateScreenSize();
			
			//页面渲染
			this.createCustomWraps();
			
			//获取wangEditor构造函数
			this.WE = window.wangEditor;
			this.createCustomToMenu(function(reParams){
				//点击菜单事件
		        reParams.menu.clickEvent = function (e) {
		        	//编辑状态=否
		        	that.clearCustomWrap(0);
		        	that.clearFunctionWrap();
		        	that.resetLayerTab({index:0});
		        	that.isEditing = false;
	            	that.currentId = false;
		        	that.layerIn({e:e,editor:reParams.editor});
		        }
			});
			
			this.wangEditorObj = new wangEditor('report-source');
			
			//拓展tag的自定义工具
//			this.WE.plugin(function(){
//				return that.customToolPlugin({that:that,this:this});
//			});
			
			return this;
		},
		
		getWang:function(){
			return this.wangEditorObj;
		},
		
		//覆盖配置
		updateOption:function(options){
			this.config = $.extend(true, this.config, options);
		},
		
		//更新屏幕尺寸
		updateScreenSize:function(){
			this.layerSize = this.getPageSize();
		},
		
		//页面初始化
		createCustomWraps:function(){
			var that = this;
			
			var temp = $('#twEditor').find('.tw-window-dataImport');
			if(temp && temp.length>0){
				//$('#twEditor').find('.tw-window-dataImport').remove();
				//$('#twEditor').find('#chartWrap').remove();
			}else{
				$('#twEditor').append(this.getDomHtml()+'<div id="chartWrap"></div>');
			}
			
		    //绑定对象内变量
		    this.customWrapsAligin();
			//左侧标签初始化
			this.$tabsWrap.slide({
				titCell:".tw-tabs-head li"
				,mainCell:".tw-tabs-body"
				,trigger:"click"
			});
		},
		
		//dom变量赋值
		customWrapsAligin:function(){
			this.$mainWrap      = $('.tw-window-dataImport');
			this.$tabsWrap      = $('.tw-window-dataImport').find('.JS_tabs');
			this.$zhibiaoWrap   = $('.tw-window-dataImport').find('.JS_zhibiao');
			this.$groupWrap     = $('.tw-window-dataImport').find('.JS_group');
			this.$yaosuWrap     = $('.tw-window-dataImport').find('.JS_yaosu');
			this.$timer         = $('.tw-window-dataImport').find('.tw-tabs-con.timer');
			this.$timerTypeWrap = $('.tw-window-dataImport').find('.JS_timerType');
			this.$yearWrap      = $('.tw-window-dataImport').find('.JS_timerYear');
			this.$monthWrap     = $('.tw-window-dataImport').find('.JS_timerMonth');
			this.$quarterWrap   = $('.tw-window-dataImport').find('.JS_timerQuarter');
			this.$functionWrap  = $('.tw-window-dataImport').find('.tw-tabs-con.function');
			this.$resultWrap    = $('.tw-window-dataImport').find('.tw-tabs-con.result');
			this.$step1         = $('.tw-window-dataImport').find('.JS_next_step.step1');
			this.$step2         = $('.tw-window-dataImport').find('.JS_next_step.step2');
			this.$step3         = $('.tw-window-dataImport').find('.JS_next_step.step3');
			this.$step4         = $('.tw-window-dataImport').find('.JS_next_step.step4');
			this.$step5         = $('.tw-window-dataImport').find('.JS_next_step.step5');
			this.$chartWrap     = $('#twEditor').find('#chartWrap');
		},
		
		//弹出数据编辑层
		layerIn:function(params){
			this.$tabsWrap.find('.step1,.step2,.step3,.step4').hide();
			//params.e, params.editor
			this.tmpData.editorParams = params;
			var that = this;
			
			this.updateScreenSize();
			
			//打开弹出层
			layer.open({
				type:1,
				title:false,
				closeBtn:0,
				shadeClose:false,
				area:[that.layerSize[2]-40+'px', that.layerSize[3]-40+'px'],
				skin:"layui-layer-nobg tw-window-show",
				content:that.$mainWrap,
				success:function(layero, index){
					//loading start
		        	that.loadLayerIdx = layer.load(1);
		        	
					that.tmpData.layerIdx = index;
					//close
					that.bindEvent({
						obj:$('.tw-close-cross'),
						name:'click',
						events:function(){
							//保存数据
							that.isEditing = false;
			            	that.currentId = false;
			            	that.tmpData = {};
							layer.close(index);
							clearInterval(that.myTimer);
						}
					})
					//edit
					if(that.isEditing){
						that.resetLayerTab({index:4});
						//计算公式和预览结果数据导入
						that.clearFunctionWrap();
						that.importResult();
					}
					//接口数据初始化
					that.zhibiaoInit();
				}
			})
		},
		
		//指标数据初始化
		zhibiaoInit:function(){
			var that = this;
			this.getJSON({
				url:that.config.basePath + "/trueDataController/getModelList.do?deptid="+that.config.deptid,
				callback:function(result){
					if(result && result.data && result.data.length>0){
						var tables = result.data
						,tableOption = '';
						for(var i=0,l=tables.length;i<l;i++){
							var selected = '';
							if(that.isEditing){
								if(that.tmpData.step1 == tables[i].modelId){
									selected = 'selected';
								}
							}
			        		tableOption += '<option '+selected+' value="'+ tables[i].modelId +'" data-tableName="'+ tables[i].tableName +'" data-tbKey="'+i+'">'+tables[i].modelName+'</option>';
			        	}
			        	that.$zhibiaoWrap.empty().append(tableOption);
			        	//单选多选
			        	that.$zhibiaoWrap.attr('multiple',false);
			        	that.$zhibiaoWrap.chosen({
			        		lang:'zh_cn'//简体中文
			        		,allow_single_deselect:true//可取消
			        		,disable_search:true//禁用检索
			        		,drop_direction:'down'//向下
						});
			        	
			        	//绑定change事件//标记初始化成功状态
			        	that.bindEvent({
			        		obj:that.$zhibiaoWrap,
			        		name:'change',
			        		events:function(){
			        			var val = $(this).val();
			        			if(val && val!=='' && val!==null){
			        				that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','yes');
			        			}else{
			        				that.$tabsWrap.find(".tw-tabs-head li").attr('load','no');
			        			}
		        				that.clearCustomWrap(0);
//			        			that.$step1.trigger('click');
								var $li = that.$tabsWrap.find(".tw-tabs-head li.on").next("li");
			        			if($li && $li.length>0){
			        				var idx = parseInt(that.$zhibiaoWrap.find('option:selected').attr("data-tbkey"));
			        				//存储对象
			        				that.tmpData.step1 = that.$zhibiaoWrap.find('option:selected').val();
			        				that.tmpData.step1Data = {data:result,idx:idx,obj:$li};
			        				that.tmpData.tableName = that.$zhibiaoWrap.find('option:selected').attr('data-tablename');
			        				that.tmpData.step1Name = that.$zhibiaoWrap.find('option:selected').text();
			        				if(!that.tmpData.chartData){
			        					that.tmpData.chartData = {};
			        				}
			        				//存储chart数据对象
			        				that.tmpData.chartData.modelId = that.tmpData.step1;
			        				that.tmpData.chartData.tableName = that.tmpData.tableName;
			        				that.tmpData.chartData.tableNameNote = that.tmpData.step1Name;
			        				//分组数据初始化
//			        				that.groupInit();
									//要素初始化
									that.yaosuInit();
			        			}
			        		}
			        	})
			        	//首次触发一下
			        	that.$zhibiaoWrap.trigger('change');
			        	
			        	//图表类型
			        	that.$tabsWrap.attr('multiple',false).find('select.JS_ctype').chosen({
			        		lang:'zh_cn'//简体中文
			        		,allow_single_deselect:true//可取消
			        		,disable_search:true//禁用检索
			        		,drop_direction:'down'//向下
						});
						that.bindEvent({
			        		obj:that.$tabsWrap.find('select.JS_ctype'),
			        		name:'change',
			        		events:function(){
			        			var val = $(this).val();
			        			if(val && val!=='' && val!==null){
			        				that.tmpData.ctype = val;
			        				//存储chart数据对象
			        				that.tmpData.chartData.type = that.tmpData.ctype;
			        			}else{
			        				
			        			}
			        			//that.clearCustomWrap(1);
			        			//要素初始化
								//that.yaosuInit();
								that.groupInit();
			        		}
			        	})
			        	that.$tabsWrap.find('select.JS_ctype').trigger('change');
			        	
			        	//ready ok
			        	//loading end
			        	layer.close(that.loadLayerIdx);
			        	
			        	//左右同步效果
//                      that.myTimer = setInterval(function(){
//                      	var idx = that.$tabsWrap.find('.tw-tabs-head li.on').attr('data-type');
//                      	that.$tabsWrap.find('.tw-tabs-body .tw-tabs-con').eq(idx).addClass('active').siblings('.tw-tabs-con').removeClass('active');
//                      }, 100);
//                      that.bindEvent({
//                      	obj:that.$tabsWrap.find('.tw-tabs-body .tw-tabs-con'),
//                      	name:'click',
//                      	events:function(){
//                      		var idx = $(this).index();
//                      		that.$tabsWrap.find('.tw-tabs-head li[data-type="'+idx+'"]').addClass('on').siblings('li').removeClass('on');
//                      	}
//                      })
			        	
//			        	if(that.isEditing){
//			        		that.groupInit();
//			        	}
					}else{
						//loading error end
						layer.close(that.loadLayerIdx);
						//关闭
						$('.tw-close-cross').trigger('click');
						layer.msg('获取数据异常');
					}
				},
				errorFun:function(){
					//todo
					that.$tabsWrap.find(".tw-tabs-head li.on").attr('load','no');
					
					//loading error end
					layer.close(that.loadLayerIdx);
					//关闭
					$('.tw-close-cross').trigger('click');
					layer.msg('获取数据异常');
				}
			})
		},
		
		//要素数据初始化
		yaosuInit:function(){
			var that = this;
			var modelId = this.tmpData.step1;
			this.getJSON({
				url:that.config.basePath + "/trueDataController/getFieldList.do?modelId="+modelId,
				callback:function(result){
					//渲染要素模块
					var field = result;
					if(field.data && field.data.fields){
						var fieldTable = '';
                        var fields = field.data.fields;
                        var fieldItem = ''
                        if(fields.length>0){
                        	var h = '<label>选择要素:</label>\
										<div>\
											<select class="JS_yaosu form-control input-sm chosen-select" multiple="multiple"></select>\
										</div>';
	                        //选择要素
	                        var tables = fields
							,tableOption = '';
							
							for(var i=0,l=tables.length;i<l;i++){
								var selected = '';
								if(that.isEditing){
									if(tables[i].name == that.tmpData.step3){
										selected = 'selected';
									}
								}
				        		tableOption += '<option '+selected+' value="'+ tables[i].name +'">'+tables[i].note+'</option>';
				        	}
							that.$tabsWrap.find('.row.yaosu').empty().append(h);
							
							that.customWrapsAligin();
							that.$yaosuWrap.empty().append(tableOption);
							
							that.$tabsWrap.find('.row.yaosu').find('select.JS_yaosu').attr('multiple',true).chosen({
				        		lang:'zh_cn'//简体中文
				        		,allow_single_deselect:true//可取消
				        		,disable_search:true//禁用检索
				        		,width:'100%'
				        		,drop_direction:'down'//向下
							});
							
							//绑定change事件
							that.bindEvent({
								obj:that.$yaosuWrap,
								name:'change',
								events:function(){
									var val = $(this).val();
									if(val && val!=='' && val!==null){
				        				that.tmpData.step3 = val;
				        				var note={};
				        				$.each(val, function(i,e) {
				        					note[e] = that.$yaosuWrap.find('option[value="'+e+'"]').text();
//				        					if(note==''){
//				        						note += that.$yaosuWrap.find('option[value="'+e+'"]').text();
//				        					}else{
//				        						note += ','+that.$yaosuWrap.find('option[value="'+e+'"]').text();
//				        					}
				        				});
//				        				note = '['+note+']';
//				        				that.tmpData.step3Note = note;
				        				
				        				//存储chart数据对象
				        				that.tmpData.chartData.fields = val;
				        				that.tmpData.chartData.fieldsNote = note;
				        				
//			        					that.clearCustomWrap(1);
				        			}else{
				        				//存储chart数据对象
				        				that.tmpData.chartData.fields = null;
				        				that.tmpData.chartData.fieldsNote = {};
				        				
//			        					that.clearCustomWrap(1);
				        			}
		        					that.groupInit();
								}
							})
							//that.$yaosuWrap.trigger('change');
                        }
                   	}
				},
				errFun:function(){
					that.$yaosuWrap.empty();
				}
			})
		},
		
		//分组数据初始化
		groupInit:function(){
			var that = this;
			var params = this.tmpData.step1Data;
			var result = params.data,
			idx = params.idx,
			obj = params.obj;
			$(obj).attr('load','no');
			if(result && result.data && result.data.length>0){
				if(result.data[idx] && result.data[idx].tyzdxList && result.data[idx].tyzdxList.length>0){
					var groupdata = result.data[idx].tyzdxList
					,groupItem = '';
					var groups = groupdata;
			        //遍历分组
					for(var i=0,l=groups.length;i<l;i++){
						var groupHD = '<label>'+groups[i].name+':</label>';
		                var groupId = groups[i].id;
		                var groupBD = '';
		                var mxs = groups[i].mxlist;
		                for(var j=0,cl=mxs.length;j<cl;j++){
			        		var selected = '';
		                	if(that.isEditing){
		                		if(mxs[j].guid == that.tmpData.step2){
		                			selected = 'selected';
		                		}
		                	}
		                	groupBD += '<option '+selected+' value="'+ mxs[j].guid +'">'+mxs[j].zbmc+'</option>';
		                }
		                groupItem += groupHD +'<div><select class="JS_group form-control input-sm chosen-select">'+ groupBD +'</select></div>';
					}
					that.$tabsWrap.find('.row.group').empty().append(groupItem);
					//单选多选
					if(that.tmpData.ctype=='2'){
		        		that.$tabsWrap.find('select.JS_group').attr('multiple',true);
					}else if(that.tmpData.ctype=='3'){
						//单选
						that.$tabsWrap.find('select.JS_group').prepend('<option value="error"></option>');
		        		that.$tabsWrap.find('select.JS_group').attr('multiple',false);
		        		that.$tabsWrap.find('select.JS_group').val('error');
					}
		        	that.$tabsWrap.find('select.JS_group').chosen({
		        		lang:'zh_cn'//简体中文
		        		,allow_single_deselect:true//可取消
		        		,disable_search:true//禁用检索
		        		,width:'100%'
		        		,drop_direction:'down'//向下
					});
					//绑定change事件
					that.bindEvent({
						obj:that.$tabsWrap.find('.row.group select'),
						name:'change',
						events:function(){
							var val = $(this).val();
							if(val==null){
								//
							}else{
								//更新绑定变量
		        				that.customWrapsAligin();
								if(that.tmpData.ctype=='2'){
									//多选
		        					var step2Name = '';
		        					$.each(val, function(i,e) {
		        						if(step2Name==''){
		        							step2Name = that.$groupWrap.find('option[value="'+e+'"]').text();
		        						}else{
		        							step2Name = step2Name+','+that.$groupWrap.find('option[value="'+e+'"]').text();
		        						}
		        					});
		        					step2Name = '['+step2Name+']';
				        			//切换到下一步
			        				//存储对象
		        					that.tmpData.step2 = val;
		        					that.tmpData.step2Name = step2Name;
								}else{
									//其他置为空
									//$(this).parentsUntil('.row').parent('.row').siblings('.row').find('select').val('error');
									//$(this).parentsUntil('.row').parent('.row').siblings('.row').find('select').trigger('chosen:updated');
									$(this).parent('div').siblings('div').find('select').val('error');
									$(this).parent('div').siblings('div').find('select').trigger('chosen:updated');
									if(val=='error'){
										//
									}else{
										//单选
										var step2Name = that.$groupWrap.find('option[value="'+val+'"]').text();
										//切换到下一步
					        			var $li = that.$tabsWrap.find(".tw-tabs-head li.on").next("li");
					        			if($li && $li.length>0){
					        				//存储对象
				        					that.tmpData.step2 = val;
				        					that.tmpData.step2Name = step2Name;
					        			}
									}
								}
							}
							
							var $sdoptions = that.$tabsWrap.find('.row.group select option:selected');
							if($sdoptions && $sdoptions.length>0){
								var list = [];
								var obj = {};
								$.each($sdoptions,function(i,e){
									if(e.value!=='error'){
										list.push(e.value.toString());
										obj[e.value.toString()] = e.innerHTML;
									}
								})
								if(list.length>0){
									//存储chart数据对象
			        				that.tmpData.chartData.diqus = list;
			        				that.tmpData.chartData.diqusNote = obj;
								}else{
									//存储chart数据对象
			        				that.tmpData.chartData.diqus = null;
			        				that.tmpData.chartData.diqusNote = {};
								}
							}else{
								//存储chart数据对象
		        				that.tmpData.chartData.diqus = null;
		        				that.tmpData.chartData.diqusNote = {};
							}
				        				
		        			that.timerInit();
						}
					})
					$(obj).attr('load','yes');
					that.$tabsWrap.find('.row.group select').trigger('change');
				}
			}
		},
		
		//时间数据初始化
		timerInit:function(){
			var that = this;
			var html = this.getTimerHtml();
			
			this.$tabsWrap.find('.tw-tabs-con.timer .tw-form').empty().append(html);
			
			//更新绑定dom对象
			this.customWrapsAligin();
			
			that.chosenInit(that.$tabsWrap.find('select.JS_timerEndYear'));
			that.chosenInit(that.$tabsWrap.find('select.JS_timerEndMonth'));
			that.chosenInit(that.$tabsWrap.find('select.JS_timerTyper'));
			that.chosenInit(that.$tabsWrap.find('select.JS_timerStartYear'));
			that.chosenInit(that.$tabsWrap.find('select.JS_timerStartMonth'));
			
			//当前年
			that.$tabsWrap.find('select.JS_timerStartYear').val(that.yearNow);
			that.$tabsWrap.find('select.JS_timerEndYear').val(that.yearNow);
			
			that.$tabsWrap.find('select.JS_timerStartYear').trigger('chosen:updated');
			that.$tabsWrap.find('select.JS_timerEndYear').trigger('chosen:updated');
			
			//绑定change关联事件
			var that = this;
			this.bindEvent({
				obj:that.$tabsWrap.find('select.JS_timerTyper'),
				name:'change',
				events:function(){
					var val = $(this).val();
					that.tmpData.timerType = val;
					//存储chart数据对象
    				that.tmpData.chartData.timerType = val;
    				
    				that.hideAllTimer();
    				
    				if(that.tmpData.ctype=='2'){
						//单
						if(val=='year'){
	    					that.showTimer(0);
	    				}
	    				if(val=='month'){
	    					that.showTimer(0);
	    					that.showTimer(1);
	    				}
					}else if(that.tmpData.ctype=='3'){
						//多
						if(val=='year'){
	    					that.showTimer(0);
	    					that.showTimer(2);
	    				}
	    				if(val=='month'){
	    					that.showTimer(0);
	    					that.showTimer(1);
	    					that.showTimer(2);
	    					that.showTimer(3);
	    				}
					}
    				
    				that.$tabsWrap.find('select.JS_timerStartYear').trigger('chosen:updated');
					that.$tabsWrap.find('select.JS_timerEndYear').trigger('chosen:updated');
    				that.$tabsWrap.find('select.JS_timerStartMonth').trigger('chosen:updated');
					that.$tabsWrap.find('select.JS_timerEndMonth').trigger('chosen:updated');
				}
			})
			that.$tabsWrap.find('select.JS_timerTyper').trigger('change');
			
			this.bindEvent({
				obj:that.$tabsWrap.find('select.JS_timerStartYear'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val!=='当前年'){
						that.$tabsWrap.find('select.JS_timerStartMonth').val(1).trigger('change').trigger('chosen:updated');
					}
					that.tmpData.startYear = val;
					//存储chart数据对象
    				that.tmpData.chartData.startYear = val;
				}
			})
			that.$tabsWrap.find('select.JS_timerStartYear').trigger('change');
			
			this.bindEvent({
				obj:that.$tabsWrap.find('select.JS_timerStartMonth'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val=='当前月'){
						that.$tabsWrap.find('select.JS_timerStartYear').val('当前年').trigger('change').trigger('chosen:updated');
					}
					that.tmpData.startMonth = val;
					//存储chart数据对象
    				that.tmpData.chartData.startMonth = val;
				}
			})
			that.$tabsWrap.find('select.JS_timerStartMonth').trigger('change');
			
			this.bindEvent({
				obj:that.$tabsWrap.find('select.JS_timerEndYear'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val!=='当前年'){
						that.$tabsWrap.find('select.JS_timerEndMonth').val(1).trigger('change').trigger('chosen:updated');
					}
					that.tmpData.endYear = val;
					//存储chart数据对象
    				that.tmpData.chartData.endYear = val;
				}
			})
			that.$tabsWrap.find('select.JS_timerEndYear').trigger('change');
			
			this.bindEvent({
				obj:that.$tabsWrap.find('select.JS_timerEndMonth'),
				name:'change',
				events:function(){
					var val = $(this).val();
					if(val=='当前月'){
						that.$tabsWrap.find('select.JS_timerEndYear').val('当前年').trigger('change').trigger('chosen:updated');
					}
					that.tmpData.endMonth = val;
					//存储chart数据对象
    				that.tmpData.chartData.endMonth = val;
				}
			})
			that.$tabsWrap.find('select.JS_timerEndMonth').trigger('change');
			
			//配置图表
			this.bindEvent({
				obj:$('.JS_btnChartSetting'),
				name:'click',
				events:function(){
					that.tmpData.chartData.width = $.trim($('input.JS_chartWidth').val());
					that.tmpData.chartData.height = $.trim($('input.JS_chartHeight').val());
					var data = that.tmpData.chartData;
					//check
					if(data.fields==null){
						layer.msg('要素必选');
					}else if(data.diqus==null){
						layer.msg('地区必选');
					}else if(data.width<=0 || data.height<=0){
						layer.msg('宽高必须设置');
					}else{
						var jsons = {};
						//type
						if(data.type=='2'){
							jsons.type = 2;
							
//							var obj = {
//								condition : {"t_nttj_data_2016.mxzbid": "=t_nttj_fbgl_zbgl_mxxx.guid"},
//								connect : "left join",
//								table : "t_nttj_data_2016,t_nttj_fbgl_zbgl_mxxx"
//							};
//							jsons.join = [obj];
							jsons.join = [];
							
							var note = [];
							$.each(data.fieldsNote, function(i,e) {
								note.push(e);
							});
							//fixed month='1' default to month=''
							if(data.timerType=='year'){
								//data.startMonth = '';
								var md1 = data.startYear;
							}else{
								//data.startMonth = '-'+data.startMonth;
								if(data.startMonth=='当前月'){
									var md1 = '当前月';
								}else{
									var md1 = data.startYear+'-'+data.startMonth;
								}
							}
							var paramArray = [
								{
//						            "condition": {
//						                "mxzbid": " in("+data.diqus.join(',')+")",
//						                "zbid": "='"+data.modelId+"'",
//						                "month": "='"+data.startMonth+"'",
//						                "year": "='"+data.startYear+"'",
//						                "season": ""
//						            },
						            "condition": {
						                "mxzbid": " in('"+data.diqus.join('\',\'')+"')",
						                "zbid": "='"+data.modelId+"'",
						                "date":"='"+md1+"'",
						                //"month": "='"+data.startMonth+"'",
						                //"year": "='"+data.startYear+"'",
						                "season": ""
						            },
						            "field": data.fields.join(','),
						            "note": note.join(','),
						            "table": data.tableName
						        }
//								,
//						        {
//						            "condition": {},
//						            "field": "zbmc",
//						            "note": "指标名称",
//						            "table": "t_nttj_fbgl_zbgl_mxxx"
//						        }
							];
							jsons.param = paramArray;
							
						}
						if(that.tmpData.ctype=='3'){
							jsons.type = 3;
							jsons.join = [];
							
							var note = [];
							$.each(data.fieldsNote, function(i,e) {
								note.push(e);
							});
							//fixed month='1' default to month=''
							if(data.timerType=='year'){
//								data.startMonth = '';
//								data.endMonth = '';
								var md2 = data.startYear;
								var md3 = data.endYear;
							}else{
//								data.startMonth = '';
//								data.endMonth = '';
								if(data.startMonth=='当前月'){
									var md2 = data.startMonth;
								}else{
									var md2 = data.startYear+'-'+data.startMonth;
								}
								if(data.endMonth=='当前月'){
									var md3 = data.endMonth;
								}else{
									var md3 = data.endYear+'-'+data.endMonth;
								}
							}
							var paramArray = [
								{
//						            "condition": {
//						                "mxzbid": "='"+data.diqus[0]+"'",
//						                "zbid": "='"+data.modelId+"'",
//						                "year":">='"+data.startYear+"'&&<='"+data.endYear+"'",
//						                "month": ">='"+data.startMonth+"'&&<='"+data.endMonth+"'",
//						            },
						            "condition": {
						                "mxzbid": "='"+data.diqus[0]+"'",
						                "zbid": "='"+data.modelId+"'",
						                "date": ">='"+md2+"'AND<='"+md3+"'",
						            },
						            "field": data.fields.join(','),
						            "note": note.join(','),
						            "table": data.tableName
						        }
							];
							jsons.param = paramArray;
						}
						
						//console.log('chartJson >>>', JSON.stringify(jsons));
						
						that.tmpData.chartFunJson = JSON.stringify(jsons);
						
						//获取数据
						///formulaController/getResult.do?function=a
						that.getJSON({
							data:JSON.stringify(jsons),
							url:that.config.basePath + '/formulaController/getResult.do?function='+JSON.stringify(jsons),
							// url:'http://192.168.0.25:5012/trueMAEC/formulaController/getResult.do?function='+JSON.stringify(jsons),
							callback:function(msg){
								//console.log(msg);
								var dd = JSON.stringify(msg.data);
								
								that.updateScreenSize();
								
								layer.open({
								  	type: 2,
								  	title: '配置图表',
							      	shadeClose: false,
								  	maxmin: false,//开启最大化最小化按钮
								  	area: [that.layerSize[2]-40+'px', that.layerSize[3]-40+'px'],
								  	content: that.config.dataPath+'?data='+encodeURIComponent(dd),//iframe的url，no代表不显示滚动条
								  	end: function(){
								  		//销毁事件
								  		var option = that.$chartWrap.find('.JS_optionChart').val();
								  		var data = that.$chartWrap.find('.JS_optionChartGroup').val();
							  			that.tmpData.chartOptionJson = option;
							  			that.tmpData.chartDataJson = data;
							  			that.$tabsWrap.find('.JS_btnChartInsert').show();
							  			that.$tabsWrap.find('.JS_btnInsertTable').show();
							  			that.bindEvent({
							  				obj:that.$tabsWrap.find('.JS_btnChartInsert'),
							  				name:'click',
							  				events:function(){
							  					that.testResultJson();
							  				}
							  			})
								  		//{"title":{"text":""},"tooltip":{"trigger":"axis"},"legend":{"data":["总量","总量排名"],"x":"left"},"toolbox":{"feature":{"saveAsImage":{}}},"xAxis":[{"type":"category","data":["南京市","无锡市","徐州市","常州市","苏州市","南通市","连云港市","淮安市","盐城市","扬州市","镇江市","泰州市","宿迁市"]}],"yAxis":[{"type":"value"}],"series":[{"name":"总量","type":"bar","stack":"总量","data":["337.8","274.9","168.8","145.6","545.4","189","100.9","120","161.1","107.1","94.1","104.1","83.7"]},{"name":"总量排名","type":"bar","stack":"总量排名","data":["2","3","5","7","1","4","11","8","6","9","12","10","13"]}]}
								  		that.bindEvent({
							  				obj:that.$tabsWrap.find('.JS_btnInsertTable'),
							  				name:'click',
							  				events:function(){
							  					that.testResultJsonInsertTable();
							  				}
							  			})
								  	}
								});
							}
						})
//						var msg = {data:[]};
						//"/trueDataController/online.do?data="+encodeURIComponent(dd);
//						var dd = JSON.stringify(msg.data);
						
//						that.updateScreenSize();
						
//						layer.open({
//						  	type: 2,
//						  	title: '配置图表',
//					      	shadeClose: false,
//						  	maxmin: false,//开启最大化最小化按钮
//						  	area: [that.layerSize[2]-40+'px', that.layerSize[3]-40+'px'],
//						  	content: that.config.dataPath+'?data='+encodeURIComponent(dd),//iframe的url，no代表不显示滚动条
//						  	end: function(){
//						  		//销毁事件
//						  		var option = that.$chartWrap.find('.JS_optionChart').val();
//						  		var data = that.$chartWrap.find('.JS_optionChartGroup').val();
//					  			that.tmpData.chartOptionJson = option;
//					  			that.tmpData.chartDataJson = data;
//					  			that.$tabsWrap.find('.JS_btnChartInsert').show();
//					  			that.$tabsWrap.find('.JS_btnInsertTable').show();
//					  			that.bindEvent({
//					  				obj:that.$tabsWrap.find('.JS_btnChartInsert'),
//					  				name:'click',
//					  				events:function(){
//					  					that.testResultJson();
//					  				}
//					  			})
//						  		//{"title":{"text":""},"tooltip":{"trigger":"axis"},"legend":{"data":["总量","总量排名"],"x":"left"},"toolbox":{"feature":{"saveAsImage":{}}},"xAxis":[{"type":"category","data":["南京市","无锡市","徐州市","常州市","苏州市","南通市","连云港市","淮安市","盐城市","扬州市","镇江市","泰州市","宿迁市"]}],"yAxis":[{"type":"value"}],"series":[{"name":"总量","type":"bar","stack":"总量","data":["337.8","274.9","168.8","145.6","545.4","189","100.9","120","161.1","107.1","94.1","104.1","83.7"]},{"name":"总量排名","type":"bar","stack":"总量排名","data":["2","3","5","7","1","4","11","8","6","9","12","10","13"]}]}
//						  		that.bindEvent({
//					  				obj:that.$tabsWrap.find('.JS_btnInsertTable'),
//					  				name:'click',
//					  				events:function(){
//					  					that.testResultJsonInsertTable();
//					  				}
//					  			})
//						  	}
//						});
					}
				}
			})
		},
		
		getDataByFun:function(params){
			var that = this;
			var fun = params.funJson;
			var group = params.groupJson;
			
			that.getJSON({
				data:fun,
				url:that.config.basePath + '/formulaController/getResult.do?function='+fun,
				callback:function(result){
					var dd = JSON.stringify(result.data);
					params.callback(dd);
				}
			})
		},
		
		showTimer:function(index){
			var that = this;
			if(index==0){
				that.$tabsWrap.find('.JS_timerStartYear').parent('.small').prev('label').show();
				that.$tabsWrap.find('.JS_timerStartYear').parent('.small').show();
			}
			if(index==1){
				that.$tabsWrap.find('.JS_timerStartMonth').parent('.small').prev('label').show();
				that.$tabsWrap.find('.JS_timerStartMonth').parent('.small').show();
			}
			if(index==2){
				that.$tabsWrap.find('.JS_timerEndYear').parent('.small').prev('label').show();
				that.$tabsWrap.find('.JS_timerEndYear').parent('.small').show();
			}
			if(index==3){
				that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').prev('label').show();
				that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').show();
			}
		},
		
		hideAllTimer:function(){
			var that = this;
			that.$tabsWrap.find('.JS_timerStartYear').parent('.small').prev('label').hide();
			that.$tabsWrap.find('.JS_timerStartYear').parent('.small').hide();
			
			that.$tabsWrap.find('.JS_timerStartMonth').parent('.small').prev('label').hide();
			that.$tabsWrap.find('.JS_timerStartMonth').parent('.small').hide();
			
			that.$tabsWrap.find('.JS_timerEndYear').parent('.small').prev('label').hide();
			that.$tabsWrap.find('.JS_timerEndYear').parent('.small').hide();
			
			that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').prev('label').hide();
			that.$tabsWrap.find('.JS_timerEndMonth').parent('.small').hide();
		},
		
		testResultJson:function(){
			var that = this;
			this.currentId = this.getUniqeId();
			var s = '<div class="charts" style="width:'+this.tmpData.chartData.width+'px;height:'+this.tmpData.chartData.height+'px">\
			<span class="chartjson"><!--TrueDATA['+ this.tmpData.chartFunJson +']--></span>\
			<span class="chartoptiongroup"><!--TrueChgp['+  this.tmpData.chartDataJson +']--></span>\
			<div class="chart-box" id="'+ this.currentId +'" style="width:'+this.tmpData.chartData.width+'px;height:'+this.tmpData.chartData.height+'px"></div></div>';
			var o = this.tmpData.editorParams;
            o.editor.command(o.e, 'insertHtml', s);
            
            if(that.tmpData.chartOptionJson){
            	var chartItem = echarts.init(document.getElementById(that.currentId));
            	chartItem.setOption(JSON.parse(that.tmpData.chartOptionJson));
            }
            
            layer.closeAll();
            
			clearInterval(that.myTimer);
		},
		
		testResultJsonInsertTable:function(){
			//插入表格
			var obj = this.getWang();
			var option = this.$chartWrap.find('.JS_optionChart').val();
//	  		var data = this.$chartWrap.find('.JS_optionChartGroup').val();
			var data = JSON.parse(option);
//			console.log(data);
			//上第一行空一格
			var legend = data.legend.data;
			//左第一列
			var xAxis = data.xAxis[0].data;
			//开始循环
			var _html = '<table class="tw-dataTable"><tbody>';
			for(var i=0,l=xAxis.length;i<l;i++){
				var $tr = '<tr>';
				if(i==0){
					//第一行第一列空格
					$tr += '<th>&nbsp;</th>';
					//第一行第二列往右
					for(var j=0,m=legend.length;j<m;j++){
						$tr += '<th>'+legend[j]+'</th>';
					}
				}else{
					//地区名称
					$tr += '<td>'+xAxis[i-1]+'</td>';
					//第一行第二列往右
					for(var j=0,m=legend.length;j<m;j++){
						var se = data.series[j].data[i-1];
						$tr += '<td>'+se+'</td>';
					}
				}
				$tr += '</tr>';
				_html += $tr;
			}
			_html += '</tbody></table>';
			
			var o = this.tmpData.editorParams;
            o.editor.command(o.e, 'insertHtml', _html);
            
            layer.closeAll();
            
			clearInterval(this.myTimer);
//			var _html = '<table class=""><tbody>\
//			<tr>\
//			<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>\
//			</tr>\
//			<tr>\
//			<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>\
//			</tr>\
//			<tr>\
//			<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>\
//			</tr>\
//			</tbody></table>';
			//塞入表格
			
		},
		
		//编辑时的导入工作
		importResult:function(){
			var that = this;
			var fixedJSON = this.dataJSON[this.currentId].functions;
			if(fixedJSON){
				var paramJSON = fixedJSON.param;
				var blocks = '';
				$.each(paramJSON[0], function(i,e) {
					var tmp = {};
					tmp[i]=e;
					blocks += '<div class="paramval-item" data-tips="'+that.tmpData.tips[that.currentId][i]+'">\
						<span class="JS_btnDelParam delparam" style="display: none;">\
							<i class="fa fa-close"></i>\
						</span>\
						<span class="JS_txtClick">'+i+'</span>\
						<textarea style="display:none">'+JSON.stringify(tmp)+'</textarea>\
					</div>';
				});
				//公式
				blocks += '<p class="tw-marginTopLine"><span>计算公式:</span><input class="JS_inputResult" type="text" placeholder="计算公式" value='+fixedJSON.result.tag+'><span class="JS_btnTagTest btn btn-primary btn-xs">运行</span> <span class="JS_btnTagReset btn btn-primary btn-xs">重置</span></p>';
			}else{
				blocks += '<p class="tw-marginTopLine"><span>计算公式:</span><input class="JS_inputResult" type="text" placeholder="计算公式"><span class="JS_btnTagTest btn btn-primary btn-xs">运行</span> <span class="JS_btnTagReset btn btn-primary btn-xs">重置</span></p>';
			}
			
			this.$functionWrap.empty().append(blocks);
			
			this.bindResultEvents();
		},
		
		chosenInit:function(obj){
			obj.chosen({
        		lang:'zh_cn'//简体中文
        		,allow_single_deselect:true//可取消
        		,disable_search:true//禁用检索
        		,drop_direction:'down'//向下
        		,width:'100%'
			});
		},
		
		//计算和结果部分事件绑定
		bindResultEvents:function(){
			var that = this;
			var fixedJSON = this.dataJSON[this.currentId].functions;
			//hover
			this.$functionWrap.find(".paramval-item").off('hover');
			this.$functionWrap.find(".paramval-item").hover(function(){
				var follow = this;
				$(this).find('.JS_btnDelParam').show();
				//tips
				layer.tips($(follow).attr('data-tips'), follow, {tips:3});
			},function(){
				$(this).find('.JS_btnDelParam').hide();
				layer.closeAll('tips');
			})
			
			//click
			this.$functionWrap.find(".JS_txtClick").off('click');
			this.$functionWrap.find(".JS_txtClick").click(function(){
				var _last = $('.JS_inputResult').val();
				$('.JS_inputResult').val(_last+$(this).text());
				$('.JS_inputResult').trigger('focus');
				//结果清空需要重新计算
				$('.tw-tabs-con.result').empty();
			})
			
			//reset
			this.$functionWrap.find('.JS_btnTagReset').off('click').click(function(){
				$('.JS_inputResult').val('');
				//结果清空需要重新计算
				$('.tw-tabs-con.result').empty();
			})
			
			//delete
			this.$functionWrap.find(".JS_btnDelParam").off('click');
			this.$functionWrap.find(".JS_btnDelParam").click(function(){
				var deleteTargetT = $(this).next('.JS_txtClick').text();
				$(this).parent('.paramval-item').remove();
				$('.JS_inputResult').val('');
				//TO:将对象中数据同步删除
				var obj = that.dataJSON[that.currentId].functions.param[0];
				var newobj = {};
				$.each(obj, function(i,e) {
					if(i!==deleteTargetT){
						newobj[i] = e;
					}
				});
				that.dataJSON[that.currentId].functions.param[0] = newobj;
				//TO:删除tips
				var tipsobj = that.tmpData.tips[that.currentId];
				var newtipsobj = {};
				$.each(tipsobj, function(i,e) {
					if(i!==deleteTargetT){
						newtipsobj[i] = e;
					}
				});
				that.tmpData.tips[that.currentId] = newtipsobj;
//				console.log(that,this);
				//结果清空需要重新计算
				$('.tw-tabs-con.result').empty();
			})
			
			//运行公式
			this.$functionWrap.find(".JS_btnTagTest").off('click');
			this.$functionWrap.find(".JS_btnTagTest").click(function(){
				if($.trim($('.JS_inputResult').val())==''){
					layer.msg('计算公式不能为空');
					return false;
				}
				
				//往接口传数据测试结果
				//载入公式
				fixedJSON.result.tag = $('.JS_inputResult').val();
				//转码
				var str = JSON.stringify(fixedJSON);
				that.getJSON({
					data:str,
					url:that.config.basePath + "/formulaController/getResult.do?function="+encodeURIComponent(str),
					callback:function(result){
						if(that.config.debugEnable){
							var val = 10 + (Math.random()*100).toFixed(2);
						}else{
							console.log(result);
						}
						that.tmpData.result = val;
						
						//切换到下一步
	        			var $li = that.$tabsWrap.find(".tw-tabs-head li.on").next("li");
	        			if($li && $li.length>0){
	        				//预览结果
	        				that.$resultWrap.empty().append('<p>结果预览:<span class="JS_tagValue tags">'+that.tmpData.result+'</span></p>\
	        				<div class="tw-btnw">\
								<span class="tw-btnm custom save JS_next_step step5">保存</span>\
							</div>');
	        				
	        				//最终确认生成标签
	        				$('.JS_next_step.step5').off('click');
	        				$('.JS_next_step.step5').click(function(){
	        					
	        					if(that.isEditing){
	        						var $delete = $('.wangeditor-menu-img-trash-o');
									$delete.trigger('click');
	        					}
	        					//insert
                                var s = '<b class="tags" data-id="'+ that.currentId +'">'+ that.tmpData.result +'</b>';
                                // 执行命令
                                var o = that.tmpData.editorParams;
                                o.editor.command(o.e, 'insertHtml', s);
                                
								//保存数据
								that.isEditing = false;
								if(!that.dataJSON[that.currentId]){
									that.dataJSON[that.currentId] = {};
								}
								that.dataJSON[that.currentId].tmpData = that.tmpData;
				            	
				            	//TODO:json加入文章数据相关存储与读取
				            	
                                //close layer
                                layer.close(that.tmpData.layerIdx);
                                
			            		that.currentId = false;
				            	that.tmpData = {};
	        				})
	        				
	        				//切换
	        				$li.trigger('click');
	        			}
					},
					errorFun:function(result){
						if(that.config.debugEnable){
							this.callback(result);
						}else{
//							console.log(result);
							layer.msg(result.error);
						}
					}
				})
			})
		},
		
		//重置容器内容
		clearCustomWrap:function(start){
			if(!start){
				start = 0;
			}
			this.$tabsWrap.find('.tw-tabs-con:gt('+start+')').find('.tw-form').not('.notClear').empty();
//			this.$tabsWrap.find('.tw-tabs-con:gt('+start+')').find('.tw-btnw .tw-btnm').not('.notClear').hide();
		},
		
		//清空运算公式和结果
		clearFunctionWrap:function(){
//      	$('.tw-tabs-con.function').empty();
//      	$('.tw-tabs-con.result').empty();
		},
		
		//切换tab
		resetLayerTab:function(params){
			this.$tabsWrap.find('.tw-tabs-head li:eq('+params.index+')').trigger('click');
		},
		
		//绑定事件
		bindEvent:function(params){
			params.obj.off(params.name).on(params.name,params.events);
		},
		
		//重新封装ajax请求数据函数
		getJSON:function(params){
			var that = this;
			$.ajax({
	            type:"POST",
	            dataType:"jsonp",
	            data:params.data?params.data:'',
	            jsonp:"callback",
	            url: params.url,
	            cache: false,
	            async: false,
	            success:function(result){
	            	if(result && (result.error==null) && (result.success==true) && result.data){
			    		//pass
			    		if(params.callback){
			    			params.callback(result);
			    		}
			    	}else{
			    		//ajax data error
			    		console.log('getJSON Error', params);
			    		if(params.errorFun){
			    			params.errorFun(result);
			    		}
			    	}
		        },
		        error:function(){
		        	if(params.errorFun){
		    			params.errorFun();
		    		}
		        }
		  	});
		},
		
		//生成唯一ID
		getUniqeId:function(){
			return this.idPrefix + (this.globalNum++);
		},
		
		//注册trueTags菜单按钮
		createCustomToMenu:function(callback){
			var that = this;
			that.WE.createMenu(function (check) {
				var menuId = 'chart';
		        if (!check(menuId)) {
		            return;
		        }
		        var editor = this;
		        // 创建 menu 对象
		        var menu = new that.WE.Menu({
		            editor: editor,
		            id: menuId,
		            title: '插入图表',
		            // 正常状态和选中装下的dom对象，样式需要自定义
		            $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-custom-icon-chart"></i></a>'),
		            $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-custom-icon-chart"></i></a>')
		        });
		        // 增加到editor对象中
		        editor.menus[menuId] = menu;
		        callback({menu:menu,editor:editor});
			})
		},
		
		//对于自定义标签的拓展插件
		customToolPlugin:function(params){
			var that = params.that;
			var editor = params.this;
	        var txt = editor.txt;
	        var $txt = txt.$txt;
	        // 说明:设置了 max-height 之后，$txt.parent() 负责滚动处理
	        var $currentTxt = editor.useMaxHeight ? $txt.parent() : $txt;
	        var $currentTag;
	
	        // 用到的dom节点
	        var isRendered = false;
	        var $toolbar = $('<div class="txt-toolbar"></div>');
	        var $triangle = $('<div class="tip-triangle"></div>');
	        var $delete = $('<a href="#"><i class="wangeditor-menu-img-trash-o"></i></a>');
	        var $edit = $('<a href="#"><i class="wangeditor-custom-icon-edit"></i></a>');
	        
	        // 渲染到页面
	        function render() {
	            if (isRendered) {
	                return;
	            }
	            
	            // 绑定事件
	            bindEvent();
	
	            // 拼接 渲染到页面上
	            $toolbar.append($triangle)
	                    .append($delete)
	                    .append($edit);
	            editor.$editorContainer.append($toolbar);
	            isRendered = true;
	        }
	        
	        // 绑定事件
	        function bindEvent() {
	            // 统一执行命令的方法
	            var commandFn;
	            function command(e, callback) {
	                if (commandFn) {
	                    editor.customCommand(e, commandFn, callback);
	                }
	            }
	
	            // 删除
	            $delete.click(function (e) {
	            	that.currentId = false;
	            	
	                commandFn = function () {
	                    $currentTag.remove();
	                };
	                command(e, function () {
	                    setTimeout(hide, 100);
	                });
	            });
	
	            $edit.click(function(e) {
	                var ct = $currentTag;
	                var tagId = $currentTag.attr('data-id');
	                that.currentId = tagId;
	                //rewrite
	                that.isEditing = true;
	                that.tmpData = that.dataJSON[that.currentId].tmpData;
	                that.clearCustomWrap(0);
	                that.layerIn({e:e,editor:editor});
	            });//edit click end
	        }
	        
	        // 显示 toolbar
	        function show() {
	            if (editor._disabled) {
	                // 编辑器已经被禁用，则不让显示
	                return;
	            }
	            if ($currentTag == null) {
	                return;
	            }
	            $(".tags").removeClass('clicked');
	            $currentTag.addClass('clicked');
	            var tagPosition = $currentTag.position();
	            var tagTop = tagPosition.top;
	            var tagLeft = tagPosition.left;
	            var tagHeight = $currentTag.outerHeight();
	            var tagWidth = $currentTag.outerWidth();
	
	            // --- 定位 toolbar ---
	            // 计算初步结果
	            var top = tagTop + tagHeight;
	            var left = tagLeft;
	            var marginLeft = 0;
	
	            var txtTop = $currentTxt.position().top;
	            var txtHeight = $currentTxt.outerHeight();
	            if (top > (txtTop + txtHeight)) {
	                // top 不得超出编辑范围
	                top = txtTop + txtHeight;
	            }
	
	            // 显示（方便计算 margin）
	            $toolbar.show();
	
	            // 计算 margin
	            var width = $toolbar.outerWidth();
	            marginLeft = tagWidth / 2 - width / 2;
	
	            // 定位
	            $toolbar.css({
	                top: top + 5,
	                left: left,
	                'margin-left': marginLeft
	            });
	            // 如果定位太靠左了
	            if (marginLeft < 0) {
	                // 得到三角形的margin-left
	                $toolbar.css('margin-left', '0');
	                $triangle.hide();
	            } else {
	                $triangle.show();
	            }
	        }
	        
	        // 隐藏 toolbar
	        function hide() {
	            if ($currentTag == null) {
	                return;
	            }
	//          $currentTag.removeClass('clicked');
	//          $currentTag = null;
	            $toolbar.hide();
	        }
	        
	        // click tag 事件
	        $currentTxt.on('click', '.tags', function (e) {
	            var $tag = $(e.currentTarget);
	
	            // 渲染
	            render();
	
//	            if ($currentTag && ($currentTag.get(0) === $tag.get(0))) {
//	                setTimeout(hide, 100);
//	                return;
//	            }
	
	            // 显示 toolbar
	            $currentTag = $tag;
	            show();
	
	            // 阻止冒泡
	            e.preventDefault();
	            e.stopPropagation();
	            
	        }).on('click keydown scroll', function (e) {
	            setTimeout(hide, 100);
	        });
	        that.WE.$body.on('click keydown scroll', function (e) {
	            setTimeout(hide, 100);
	        });
		},
		
		//获取窗口大小
		getPageSize:function(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY}else{if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight}}var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth}else{windowWidth=self.innerWidth}windowHeight=self.innerHeight}else{if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight}else{if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight}}}if(yScroll<windowHeight){var pageHeight=windowHeight}else{var pageHeight=yScroll}if(xScroll<windowWidth){var pageWidth=xScroll}else{var pageWidth=windowWidth}var arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize}
	}//prototype end
	
	var TrueChartsObj = new trueCharts().init({
//		debugEnable:false
//		,basePath:'http://61.155.85.74:3333/TrueDPS'
	});
	
	//拓展给jquery
	$.fn.TC = trueCharts;
})();